var vm = new Vue({
    el: '#rrapp',
    data: {
        q:{
            page:1,
            limit:10,
            searchParam:''
        },
        list:null,
        fields:null,
        pages:null,
        colMod:[
            {
                label: 'id',
                name: 'id',
                index: 'id',
                key: true,
                hidden: true,
                width:40
            },
            {
                label: '所属集团',
                name: 'companyName',
                index: 'companyName',
                width:80
            },
            {
                label: '门店名称',
                name: 'name',
                index: 'name',
                width:80
            },
            {
                label: '配置',
                name: 'config',
                index: 'config',
                width:80
            }
        ],
        row:[],
        configModal:false,
        fieldList:[],
        show:false,
        detail:null,
        configList:[],
        submit:false,
        fieldModal:false,
        fieldEditDisable:false,
        submitEditLoading:false,
        itemStatus:false,
        delStatus:false,
        initStatus:true,
        tableStatus:false,
        multipleStatus:false,
        branchIdList:[],
        oldName:'',
        oldType:'',
        oldLevel:'',
        filedType:[],

    },
    created(){
        this.init();
    },
    mounted(){
        this.createTable();
    },
    methods: {
        /*初始化数据*/
        init(){
            var that=this;
            Ajax.request({
                url: "../org/store/config/list",
                params: JSON.stringify(that.q),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    //console.log(r)
                    that.list=r.data.list;
                    that.fields=r.data.fields;
                    that.pages=r.data.page;
                    that.buildData();
                    setTimeout(function () {
                        that.initStatus=false;
                    },1500)
                }
            });
        },
        /*初始化页面准备数据*/
        clearInitData(){
            this.list=null;
            this.fields=null;
            this.pages=null;
            this.colMod=[
                {
                    label: 'id',
                    name: 'id',
                    index: 'id',
                    key: true,
                    hidden: true,
                    width:40
                },
                {
                    label: '所属集团',
                    name: 'companyName',
                    index: 'companyName',
                    width:80
                },
                {
                    label: '门店名称',
                    name: 'name',
                    index: 'name',
                    width:80
                },
                {
                    label: '配置',
                    name: 'config',
                    index: 'config',
                    width:80
                }
            ];
            this.row=[];
            this.configModal=false;
            this.fieldList=[];
            this.show=false;
            this.detail=null;
            this.configList=[];
            this.submit=false;
            this.fieldModal=false;
            this.fieldEditDisable=false;
            this.submitEditLoading=false;
            this.itemStatus=false;
            this.delStatus=false;
            this.tableStatus=false;
            this.oldName='';
            this.oldType='';
            this.oldLevel='';
        },
        /*构建表格数据*/
        buildData(){
            var that=this;
            console.log("list",that.list)
            console.log("fields",that.fields)
            // console.log("pages",that.pages)
            that.fields.filter(e=>{
                var mod={
                    label: e.type.name+"/"+e.label+"/"+e.level,
                    name: e.value,
                    index: e.value,
                    width:40
                };
                that.colMod.push(mod)
            });
            that.list.filter(e=>{
                var str='{"id":"'+e.id+'","companyName":"'+e.companyName+'","name":"'+e.name+'","config":"'+(e.config=='0'?'未首次配置':(e.config=='1'?'已完整配置':'新增未配置'))+'",';
                e.configs.filter(c=>{
                    that.fields.filter((f,i)=>{
                        if (c.fieldId==f.value){
                            str+='"'+f.value+'":"'+(c.value=='0'?"<span class='appearance_style not_style'>否<span>":"<span class='appearance_style ok_style'>是<span>")+'",'
                        }
                    })
                })
                str=str.substring(0,str.length-1);
                str+='}'
                str.trim();
                that.row.push(JSON.parse(str))
            })

            $("#pages").remove();
            $("body").append('<div id="pages"></div>');
            layui.use(['laypage', 'layer'], function() {
                var page = layui.laypage;
                page({
                    cont: 'pages'
                    ,pages: that.pages.totalPage
                    ,skip: true
                    ,curr: that.pages.currPage
                    ,last: that.pages.totalPage
                    ,jump:function(o,e){
                        that.nextPage(o,e)
                    }
                });
            })
        },
        /*创建表格*/
        createTable(){
            var that=this;
            $("#company_table").Grid({
                datatype:'local',
                colModel:that.colMod,
                rowNum:-1,
                rowList:null,
                pager:null,
                localReader:{
                    root: function(obj) { return that.row; }
                }
            })
            setTimeout(function () {
                that.tableStatus=true;
            },2000)

        },
        /*强制刷新表头*/
        reTableTitle(){
            var that=this;
            $("#gbox_company_table").remove();//强制清除grid容器的html,这个标签在渲染表格后由jqgrid创建的表格最外层标签
            $(".table").append('<table id="company_table"></table>');//再新增一个grid的渲染容器
            $("#company_table").Grid({
                datatype:'local',
                colModel:that.colMod,
                rowNum:-1,
                rowList:null,
                pager:null,
                localReader:{
                    root: function(obj) { return that.row; }
                }
            })
            setTimeout(function () {
                that.tableStatus=true;
            },2000)
        },
        /*打开门店配置模态框*/
        setConfig(){
            var that=this;
            var id=getSelectedRows("#company_table");
            if (id.length>1){
                that.branchIdList=id;
                that.multipleStatus=true;
            }
            if (id.length==0){
                return;
            }
            var data={
                id:id[0]
            }
            Ajax.request({
                url: "../org/store/config/query",
                params: JSON.stringify(data),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    // console.log(r)
                    that.configList=r.data.detail.configs;
                    if (that.configList.length==0){
                        layer.alert("暂未添加配置字段，请在【编辑】中添加门店配置字段！")
                        return
                    }
                    if (that.multipleStatus){
                        that.configList.forEach(e=>{
                            e.value="1"
                        })
                    }
                    that.detail=r.data.detail;
                    that.configModal=true;
                }
            });
        },
        /*关闭模态框*/
        closeConfigModal(){
            if (this.configModal){
                this.initStatus=true;
                this.multipleStatus=false;
                this.branchIdList=[];
                this.clearInitData();
                this.init();
                this.reTableTitle();
                this.configModal=false;
            }
            if (this.fieldModal){
                this.initStatus=true
                this.clearInitData();
                this.init();
                this.reTableTitle();
                this.fieldModal=false;
            }
        },
        /*清除数据*/
        clearData(){

            this.table=null;
            this.list=null;
            this.fields=null;
            this.pages=null;
            this.colMod=[
            {
                label: 'id',
                name: 'id',
                index: 'id',
                key: true,
                hidden: true,
                width:40
            },
            {
                label: '所属集团',
                name: 'companyName',
                index: 'companyName',
                width:80
            },
            {
                label: '门店名称',
                name: 'name',
                index: 'name',
                width:80
            },
            {
                label: '配置',
                name: 'config',
                index: 'config',
                width:80
            }
        ];
            this.row=[];
        },
        /*打开字段模态框*/
        editField(){
            var that=this
            that.fieldModal=true
            if (that.fieldList.length==0){
                Ajax.request({
                    url: "../org/store/field/list",
                    type: "POST",
                    successCallback: function (r) {
                        r.data.filter(e=>{
                            e.nameDisable="true"
                            e.fieldDisable="true"
                            that.fieldList.push(e)
                        })
                        // console.log(that.fieldList)
                    }
                });
                Ajax.request({
                    url: "../org/store/config/type",
                    type: "GET",
                    successCallback: function (r) {
                        that.filedType=r.list
                    }
                });
            }
        },
        /*删除字段*/
        del(e){
            var that=this
            that.delStatus=true
            if (e.id!=0){
                Ajax.request({
                    url: "../org/store/field/del?id="+e.id,
                    type: "GET",
                    contentType: "text/html;charset=utf-8",
                    successCallback: function (r) {
                        setTimeout(function () {
                            that.fieldList=[];
                            that.editField();
                            that.delStatus=false
                        },500)
                    }
                });
                setTimeout(function () {
                    if (that.delStatus){
                        that.fieldList=[];
                        that.editField();
                        that.delStatus=false
                    }
                },2000)
            }else {
                this.removeItem();
            }
        },
        /*修改字段*/
        edit(e){
            this.oldName=''
            this.oldType='';
            this.oldLevel='';
            this.oldName=e.name
            this.oldType=e.type;
            this.oldLevel=e.level;
            if (this.fieldList){
                this.fieldEditDisable=true
                for (let i=0;i<this.fieldList.length;i++){
                    if (e.id==this.fieldList[i].id){
                        this.fieldList[i].nameDisable="false"
                    }
                }
            }
        },
        /*提交修改字段*/
        editSubmit(e){
            if (e.name=='' || e.fieldId==''){
                layer.msg("字段不能为空")
                return;
            }
            var that=this

            if (!that.checkNameAndID(e)){
                return
            }
            that.submitEditLoading=true
            if (that.oldName==e.name
                && that.oldType==e.type
                && that.oldLevel==e.level){
                that.fieldList=[];
                that.editField();
                that.fieldEditDisable=false
                that.submitEditLoading=false
                return;
            }
            console.log("/field/upd",e)
            Ajax.request({
                url: "../org/store/field/upd",
                params: JSON.stringify(e),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    setTimeout(function () {
                        if (that.fieldList){
                            that.fieldList=[];
                            that.editField();
                            that.fieldEditDisable=false
                            that.submitEditLoading=false
                        }
                    },500)
                },
            });
            setTimeout(function () {
                if (that.submitEditLoading && that.fieldEditDisable){
                    that.fieldList=[];
                    that.editField();
                    that.fieldEditDisable=false
                    that.submitEditLoading=false
                }
            },2000)
        },
        /*添加新的字段输入框*/
        addItem(){
            this.itemStatus=true
            this.fieldEditDisable=true
            var obj={
                fieldDisable: "false",
                fieldId: "",
                id: 0,
                name: "",
                nameDisable: "false",
                type: 0,
                level:1
            }
            this.fieldList.push(obj);
        },
        /*移除添加新字段输入框*/
        removeItem(){
            if (this.itemStatus){
                this.itemStatus=false
                this.fieldEditDisable=false
                this.fieldList.pop()
            }
        },
        /*添加字段提交*/
        addField(e){
            var that=this
            if (!that.checkNameAndID(e)){
                return
            }
            that.submitEditLoading=true;
            //console.log(e)
            Ajax.request({
                url: "../org/store/field/add",
                params: JSON.stringify(e),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    setTimeout(function () {
                        if (that.fieldList){
                            that.fieldList=[];
                            that.editField();
                            that.fieldEditDisable=false
                            that.itemStatus=false
                            that.submitEditLoading=false
                        }
                    },500)
                },
            });
            setTimeout(function () {
                if (that.submitEditLoading && that.fieldEditDisable && that.itemStatus){
                    if (that.fieldList){
                        that.fieldList=[];
                        that.editField();
                        that.fieldEditDisable=false
                        that.itemStatus=false
                        that.submitEditLoading=false
                    }
                }
            },2000)

        },
        checkNameAndID(e){
            var regExp=new RegExp(/[\u4e00-\u9fa5]/);
            var nameRegx=new RegExp(/(,)|(-)|(，)/);
            if (regExp.test(e.fieldId)){
                layer.msg("字段标识请输入字母或数字")
                return false;
            }
            if (nameRegx.test(e.name) || nameRegx.test(e.fieldId) || nameRegx.test(e.level)){
                layer.msg("非法字段标识符',|-'");
                return false;
            }
            if (e.name=='' || e.fieldId=='' || e.level==='' || e.type===''){
                layer.msg("字段或标识符不能为空1");
                return false;
            }
            if (e.name==null || e.fieldId==null || e.level==null || e.type==null){
                layer.msg("字段或标识符不能为空2")
                return false;
            }
            if (e.name==undefined || e.fieldId==undefined || e.level==undefined || e.type==undefined){
                layer.msg("字段或标识符不能为空3")
                return false;
            }
            return true;
        },
        /*搜索查询门店*/
        query(){
            this.q.page=1;
            this.q.limit=10;
            this.clearData();
            this.init();
            this.reloadTable();
        },
        /*重新加载表格数据*/
        reloadTable(){
            var that=this;
            $("#company_table").setGridParam({data: that.row}).trigger('reloadGrid');
        },
        /*清空搜索框*/
        reloadSearch(){
            this.q.searchParam='';
            this.query();
        },
        /*分页*/
        nextPage(o,e){
            //console.log(e)
            if (e){
                return
            }
            this.q.page=o.curr
            this.clearData();
            this.init();
            this.reloadTable();
        },
        /*提交门店配置*/
        submitConfig(){
            var that=this;
            if (that.multipleStatus){
                layer.confirm("批量配置会使门店的历史配置项变回默认值,您确定需要这么做?",{btn:["确定","取消"],btn1:function (index){
                        that.submit=true;
                        var data=[];
                        that.branchIdList.forEach(e=>{
                            that.configList.forEach(t=>{
                                var  obj={
                                    branchId:e,
                                    storeId:t.id,
                                    val:t.value
                                };
                                data.push(obj)
                            })
                        });
                        Ajax.request({
                            url: "../org/store/config/set",
                            params: JSON.stringify(data),
                            type: "POST",
                            contentType: "application/json",
                            successCallback: function (r) {
                                setTimeout(function () {
                                    that.submit=false;
                                    that.multipleStatus=false;
                                    that.branchIdList=[];
                                    that.closeConfigModal();
                                    that.clearData();
                                    that.init();
                                    that.reloadTable();
                                },1000)
                            }
                        });
                        layer.close(index);
                },
                btn2:function (index){
                    layer.close(index);
                }},
            );
            return;
            }
            that.submit=true;
            var data=[];
            var branchId=that.detail.id;
            that.configList.filter(e=>{
                var  obj={
                    branchId:branchId,
                    storeId:e.id,
                    val:e.value
                };
                data.push(obj)
            });
            Ajax.request({
                url: "../org/store/config/set",
                params: JSON.stringify(data),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    setTimeout(function () {
                        that.submit=false;
                        that.closeConfigModal();
                        that.clearData();
                        that.init();
                        that.reloadTable();
                    },1000)
                }
            });
        },
        /*门店配置状态修改*/
        change(e){
            for (let i=0;i<this.configList.length;i++){
                if (e.id==this.configList[i].id){
                    if (e.value==1){
                        this.configList[i].value='0';
                    }else {
                        this.configList[i].value='1';
                    }
                }
            }
        }
    },
});